/*
 * Xiaobo Yang, STFC e-Science Centre, Daresbury Laboratory, UK
 * Created: 30 April 2007
 * Last modified: 3 July 2007
 * 
 */
package uk.ac.dl.esc.gtg.myportlets.fileupload;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletConfig;
import javax.portlet.PortletContext;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.portlet.PortletFileUpload;
import org.apache.commons.io.FilenameUtils;

import uk.ac.dl.esc.gtg.myportlets.fileupload.FileUploadProgressListener;


public class FileUploadPortlet extends GenericPortlet {
  private String viewUrl = null;
  private long uploadMaxSize = 0;

  /**
   * @see javax.portlet.Portlet#init(javax.portlet.PortletConfig)
   */
  public void init(PortletConfig config) throws PortletException {
    super.init(config);

    viewUrl = config.getInitParameter("fileupload_view_template");
    
    String m = config.getInitParameter("fileupload_upload_maxsize");
    try {
      uploadMaxSize = Integer.parseInt(m) * 1048576;
    }
    catch (NumberFormatException nfe) {
      uploadMaxSize = 10485760;
      getPortletContext().log("[FileUploadPortlet] - failed to read in filetransfer_upload_maxsize, set to 10MB");
    }
  }

  public void processAction(ActionRequest request, ActionResponse response)
					throws PortletException, IOException {
    PortletMode pMode = request.getPortletMode();
    if (pMode.equals(PortletMode.VIEW)) {
      // upload -- enctype="multipart/form-data"
      if (PortletFileUpload.isMultipartContent(request))
        doUpload(request, response);
    }

  }

  /**
   * Serve up the <code>view</code> mode.
   * 
   * @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest,
   *      javax.portlet.RenderResponse)
   */
  public void doView(RenderRequest request, RenderResponse response)
      throws PortletException, IOException {
    // Set the MIME type for the render response
    response.setContentType(request.getResponseContentType());

    // Invoke the JSP to render
    PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(
        viewUrl);
    rd.include(request, response);

    // DWR support
    PortletRequestDispatcher rd2 = getPortletContext()
        .getRequestDispatcher("/dwr/");
    rd2.include(request, response);

  }


  private void doUpload(ActionRequest request, ActionResponse response) {
    PortletContext context = getPortletContext();
    context.log("[FileUploadPortlet] doUpload() called");

    try {
      DiskFileItemFactory factory = new DiskFileItemFactory();
      PortletFileUpload pfu = new PortletFileUpload(factory);
      pfu.setSizeMax(uploadMaxSize); // Maximum upload size
      pfu.setProgressListener(new FileUploadProgressListener());

      //get the FileItems
      String fieldName = null;
      
      List fileItems = pfu.parseRequest(request);
      Iterator iter = fileItems.iterator();
      while (iter.hasNext()) {
        FileItem item = (FileItem)iter.next();
        // retrieve hidden parameters if item is a form field
        if (item.isFormField()) {
          fieldName = item.getFieldName();
        }
        else { // item is not a form field, do file upload
          String s = item.getName();
          s = FilenameUtils.getName(s);

          String tempDir = System.getProperty("java.io.tmpdir");
          File serverSideFile = new File(tempDir, s);
          item.write(serverSideFile);
          item.delete();
          context.log("[FileUploadPortlet] - file " + s
				+ " uploaded successfully to " + tempDir);
        }
      }
    }
    catch (FileUploadException fue) {
      context.log("[FileUploadPortlet] - failed to upload file - "
							+ fue.toString());
      return;
    }
    catch (Exception e) {
      context.log("[FileUploadPortlet] - failed to upload file - "
							+ e.toString());
      return;
    }

  }


}
